<?php
/**
 * Created by PhpStorm.
 * User: 69571
 * Date: 2019/8/8
 * Time: 19:13
 */

namespace app\controllers;


use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\Rbac;
use app\models\Users;
use app\models\Shop;


class AdminController extends Controller
{

    /*
     *取消yii 框架自带的头和尾样式
    */
    public $enableCsrfValidation = false;

    /*
     * 登录页面
     * */
    public function actionLogin()
    {
        return $this->renderPartial('login');
    }

    /**
     * 登录操作
     */
    public function actionLogindo()
    {
        $session = Yii::$app->session;
        $session->open();
        $request = Yii::$app->request;
        $formData = $request->post();
        $u_email = $formData['u_email'];
        $u_pwd = md5($formData['u_pwd']);
        $result = Yii::$app->db->createCommand("SELECT * FROM `users` WHERE u_email='$u_email' and u_pwd = '$u_pwd'")->queryOne();
        if ($result) {
            $session->set('adminuser', $result);
            $time = date('Y-m-d H:i:s', time());
            Yii::$app->db->createCommand()->insert('loginlog', [
                'user_name' => $result['u_name'],
                'starttime' => $time,
            ])->execute();
            echo "<script>alert('登录成功！');location.href='/admin/index'</script>";
        } else {
            echo "<script>alert('登录失败！');location.href='/admin/login'</script>";
        }
    }

    /**
     *  注册时 唯一性验证
     */
        public function actionEmail_one(){
            $email = $_POST['eamil'];
            $email_one = Yii::$app->db->createCommand("SELECT * FROM users WHERE u_email='$email'")->queryOne();
            if(!$email_one){
                return json_encode(['code'=>500,'msg'=>'该邮箱已存在,请您做更换']);
            }else{
                return json_encode(['code'=>200,'msg'=>'您可以使用该邮箱']);
            }
        }
    /**
     *
     *  查看个人信息值
     */
    public function actionUserinfo(){
        $session = Yii::$app->session;
        $session->open();
       $userinfo = $session->get('adminuser');

        return $this->renderPartial('userinfo',['userInfo'=>$userinfo]);
    }

    /**
     * @return string
     * 注册
     */
    public function actionLoginadd()
    {
        $request = Yii::$app->request;
        $formData = $request->post();
        $result = Users::loginadd($formData);
        if ($result == 1) {
            echo "<script>alert('注册成功！');location.href='/admin/login'</script>";
        } else {
            echo "<script>alert('注册失败！');location.href='/admin/login'</script>";
        }
    }

    /**
     * @throws \yii\db\Exception
     * 退出登录
     */
    public function actionLoginout()
    {
        $session = Yii::$app->session;
        $session->open();
        return $session->remove('adminuser') ? 1 : 0;
    }

    /*
     * 首页展示
     * */
    public function actionIndex()
    {
        $session = Yii::$app->session;
        $session->open();
        $adminuser = $session->get('adminuser');
        return $this->renderPartial('index', ['adminuser' => $adminuser]);
    }

    /*
     * 我的桌面
     * */
    public function actionWelcome()
    {
        return $this->renderPartial('welcome');
    }

    /**
     * @return string
     *  资源管理
     */

    public function actionArticle_list()
    {
        return $this->renderPartial('article-list');
    }

    /**
     *  资源添加
     */
    public function actionArticle_add()
    {
        return $this->renderPartial('article-add');
    }

    /**
     * 修改资源信息
     */
    public function actionArticle_change()
    {
        return $this->renderPartial('article-change');
    }
    /**
     *
     * 意见反馈
     */
    public function actionFeedback_list(){
        return $this->renderPartial('feedback-list');
    }
    /**
     *  图片管理
     */
    public function actionPicture_list()
    {
        return $this->renderPartial('picture-list');
    }

    /**
     * 图片修改
     */
    public function actionPicture_change()
    {
        return $this->renderPartial('picture-change');
    }

    /**
     *  图片添加
     *
     */
    public function actionPicture_add()
    {
        return $this->renderPartial('picture-add');
    }

    /**
     *
     * 图片展示
     */
    public function actionPicture_show()
    {
        return $this->renderPartial('picture-show');
    }

    /**
     *  品牌管理
     */
    public function actionProduct_brand()
    {
        $logo_arr = Yii::$app->db->createCommand("SELECT * FROM logos")->queryAll();

       $count = count($logo_arr);
        return $this->renderPartial('product-brand',['logoArr'=>$logo_arr,'count'=>$count]);
    }

    /**
     *   分类管理
     */
    public function actionProduct_category()
    {
        // 查询出 分类管理的 排序

        return $this->renderPartial('product-category');
    }

    /**
     * 添加分类
     */
    public function actionProduct_category_add()
    {
        return $this->renderPartial('product-category-add');
    }

    /**
     *产品管理
     *
     */
    public function actionProduct_list()
    {

        $type_id = isset($_GET['type_id'])?$_GET['type_id']:'';
        $shop  = new Shop();
        $datas = $shop->types();
        $data = $shop->shop_arr($type_id);

        return $this->renderPartial('product-list', ['data' => $data,'datas'=>$datas]);
    }

    /**
     * 产品添加
     *
     */
    public function actionProduct_add()
    {
        $data = Yii::$app->db->createCommand('SELECT * FROM type')->queryAll();
        return $this->renderPartial('product-add', ['data' => $data]);
    }

    /**
     *  产品修改
     *
     */
    public function actionProduct_change()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $res = Yii::$app->db->CreateCommand("SELECT * FROM shop where shop_id = '$id'")->queryOne();
        $data = Yii::$app->db->createCommand('SELECT * FROM type')->queryAll();

        return $this->renderPartial('product-change', ['res' => $res, 'data' => $data]);
    }

    /**
     * 会员列表
     */
    public function actionMember_list()
    {
        $result = Yii::$app->db->createCommand('SELECT * FROM vip where `is_vip`=1')->queryAll();
        foreach ($result as $key=>$v){
                $jf = $v['vip_jf'];
                if($jf>=500){
                    $result[$key]['vips_name']='荣耀会员';
                }else{
                    $vip = Yii::$app->db->createCommand("SELECT rank_name FROM vip_rank WHERE $jf  BETWEEN min_points AND max_points ")->queryOne();
                    $result[$key]['vips_name'] =$vip['rank_name'];
                }
        }

        $count = Yii::$app->db->createCommand("select * from vip where `is_vip`=1")->query()->rowCount;
        return $this->renderPartial('member-list', [
            'result' => $result,
            'count' => $count
        ]);
    }

    /**
     * 添加会员
     */
    public function actionMember_add()
    {
        return $this->renderPartial('member-add');
    }



    /**
     *  查看会员信息
     */
    public function actionMember_show()
    {
        $request = Yii::$app->request;
        $id = $request->post();
        print_r($id);die();
        $result = Yii::$app->db->createCommand('SELECT * FROM `vip` WHERE vip_id=$id')->queryOne();

        return $this->renderPartial('member-show');
    }

    /**
     * @return string
     * @throws \yii\db\Exception
     *
     */
    public function actionVip_show(){
        $result = Yii::$app->db->createCommand('SELECT * FROM `vip_rank`')->queryAll();
        return $this->renderPartial('member-vipshow',['result'=>$result]);
    }

    /**
     * 删除的会员
     */
    public function actionMember_del()
    {
        $result = Yii::$app->db->createCommand('SELECT * FROM vip where `is_vip`=0')->queryAll();
        $count = Yii::$app->db->createCommand("select * from vip where `is_vip`=0")->query()->rowCount;
        return $this->renderPartial('member-del', [
            'result' => $result,
            'count' => $count
        ]);
    }

    /**
     * 角色管理
     */
    public function actionAdmin_role() {
        $rbac = new Rbac;
        $admin_role_arr = $rbac->admin_role_arr();

        return $this->renderPartial('admin-role',['role_arr'=>$admin_role_arr]);
    }


    /**
     * 角色添加
     */
    public function actionAdmin_add() {
        $rbac = new Rbac;
        $role_arr = $rbac->Role();

        return $this->renderPartial('admin-add',['role_arr'=>$role_arr]);
    }

    /**
     * 权限管理
     */
    public function actionAdmin_permission()
    {
        return $this->renderPartial('admin-permission');
    }

    /**
     * 添加角色
     */
     public function actionAdmin_role_add(){
        $rbac = new Rbac;
        $power_arr = $rbac->power_arr();
        $role_arr = $rbac->role_arr();

        return $this->renderPartial('admin-role-add',['power_arr'=>$power_arr]);
    }

    /**
     *  管理员 列表
     */
    public function actionAdmin_list()
    {
        $rbac = new Rbac;
        $user_arr = $rbac->user_list();
        return $this->renderPartial('admin-list', ['user_arr' => $user_arr]);
    }

    /**
     *
     *  管理员修改
     */
    public function actionAdmin_change()
    {
        $rbac = new Rbac;
        $role_arr = $rbac->Role();
        $uid = $_GET['uid'];
        $user_one = $rbac->user_one($uid);

        return $this->renderPartial('admin-change', ['role_arr' => $role_arr, 'one' => $user_one]);
    }

    /**
     *  修改管理员密码
     */
    public function actionChange_password()
    {
        return $this->renderPartial('change-password');
    }

    /**
     *  修改角色信息
     */
   public function actionAdmin_role_change(){
        $id = $_GET['id'];
        $rbac = new Rbac;
        $role_one = $rbac->role_one($id);
        $power_arr = $rbac->power_arr();

        return $this->renderPartial('admin-role-change',['role_one'=>$role_one,'power_arr'=>$power_arr]);
    }

    /**
     *  添加权限
     */
    public function actionAdmin_permission_add()
    {
        return $this->renderPartial('admin-permission-add');
    }

    /**
     *  修改权限节点权限
     */
    public function actionAdmin_permission_change()
    {
        return $this->renderPartial('admin-permission-change');
    }

     /**
     * 订单管理页面
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionOrder_list()
    {
        $data = Yii::$app->db->createCommand("select * from shop_order where order_status in (1,2,3) ")->queryAll();
        $count = Yii::$app->db->createCommand("select * from shop_order where order_status in (1,2,3)")->query()->rowCount;
        foreach ($data as $k => $v) {

            $id = $v['submitter'];
            $name = Yii::$app->db->createCommand("select * from users where id=$id")->queryOne();
            $data[$k]['submitter'] = $name['u_name'];
            $arr = explode(',', $v['shop_name']);
            foreach ($arr as $value) {
                $idALL[] = explode('-', $value);
            }
            foreach ($idALL as $shop) {
                $good = Yii::$app->db->createCommand("select  shop_id,shop_name,shop_img from shop where shop_id=:id")
                    ->bindValue(':id', $shop[0])
                    ->queryOne();
                $good['num'] = $shop[1];
                $goods[] = $good;
            }
            $data[$k]['shop_name'] = $goods;
            $idALL = [];
            $goods = [];
        }
        return $this->renderPartial('order-list', ['data' => $data, 'count' => $count]);
    }

    /**
     * 退款列表
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionOrder_refund()
    {
        $data = Yii::$app->db->createCommand("select * from shop_order where order_status in (4,5) ")->queryAll();
        $count = Yii::$app->db->createCommand("select * from shop_order where order_status in (4,5) ")->query()->rowCount;
        foreach ($data as $k => $v) {
            $id = $v['submitter'];
            $name = Yii::$app->db->createCommand("select * from users where id=$id")->queryOne();
            $data[$k]['submitter'] = $name['u_name'];
            $arr = explode(',', $v['shop_name']);
            foreach ($arr as $value) {
                $idALL[] = explode('-', $value);
            }
            foreach ($idALL as $shop) {
                $good = Yii::$app->db->createCommand("select  shop_id,shop_name,shop_img from shop where shop_id=:id")
                    ->bindValue(':id', $shop[0])
                    ->queryOne();
                $good['num'] = $shop[1];
                $goods[] = $good;
            }
            $data[$k]['shop_name'] = $goods;
            $idALL = [];
            $goods = [];
        }
        return $this->renderPartial('order-refund', ['data' => $data, 'count' => $count]);
    }

    /**
     * 退款功能
     * @throws \yii\db\Exception
     */
    public function actionOrderrefund()
    {
        $id = Yii::$app->request->post('id', '1');
        $res = Yii::$app->db->createCommand()
            ->update('shop_order', ['order_status' => '5'], 'order_id=' . $id)
            ->execute();
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 订单合并页面
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionOrder_merge()
    {
        $data = Yii::$app->db->createCommand("select order_id,order_number,order_status from shop_order where order_status in (1,2,3) ")->queryAll();
        return $this->RenderPartial('order-merge', ['data' => $data]);
    }

    /**
     * 合并
     * @param $z
     * @param $c
     * @return string
     */
    function merge($z,$c)
    {
        foreach ($z as $k => $v) {
            foreach ($c as $key => $val) {
                    if ($v[0]==$val[0]){
                        $s[0]=$val[0];
                        $s[1]=$v[1]+$val[1];
                        if (isset($res[$k])){
                            $res[$k][0]=$v[0];
                            $res[$k][1]=$res[$k][1]+$val[1];
                        }else{
                            $res[$k]=$s;
                        }
                        unset($c[$key]);
                    }
            }
        }
        foreach ($z as $k => $v) {
            foreach ($res as $key => $val) {
                if ($v[0]==$val[0]){
                   unset($z[$k]);
                }
            }
        }
        foreach ($z as $v){
            array_push($res,$v);
        }
        foreach ($c as $v){
            array_push($res,$v);
        }
        foreach ($res as $v){
           $arr[]= implode('-',$v);
        }

        return implode(',',$arr);
    }


    /**
     * 订单合并功能
     * @throws \yii\db\Exception
     */
    public function actionOrdermerge()
    {
        $cid = Yii::$app->request->post('cid');
        $zid = Yii::$app->request->post('zid');
        $zorder = Yii::$app->db->createCommand("select shop_name,order_amount,order_status from shop_order where order_number = '$cid' ")->queryOne();
        $corder = Yii::$app->db->createCommand("select shop_name,order_amount,order_status from shop_order where order_number = '$zid' ")->queryOne();
        if ($corder && $zorder) {
            $order_status1 = $zorder['order_status'];
            $order_status2 = $corder['order_status'];
            if ($order_status1 == $order_status2) {
                $str = $zorder['shop_name'] . "," . $corder['shop_name'];
                $zzorder[] = explode(',', $zorder['shop_name']);
                $ccorder[] = explode(',', $corder['shop_name']);
                foreach ($zzorder as $val) {
                    foreach ($val as $v) {
                        $zar[] = explode('-', $v);
                    }
                }
                foreach ($ccorder as $val) {
                    foreach ($val as $v) {
                        $car[] = explode('-', $v);
                    }
                }
                $str=$this->merge($zar,$car);
                $order_amount = $corder['order_amount'] + $zorder['order_amount'];
                Yii::$app->db->createCommand("DELETE FROM `shop_order` WHERE order_number = '$cid'")
                    ->execute();
                $res = Yii::$app->db->createCommand()
                    ->update('shop_order', ['order_amount' => $order_amount, 'shop_name' => $str], 'order_number=' . $zid)
                    ->execute();
                if ($res) {
                    return 1;
                } else {
                    return 2;
                }
            } else {
                return 3;
            }
        } else {
            return 0;
        }


    }



    /**
     * 订单删除
     * @throws \yii\db\Exception
     */
    public function actionOrderdel()
    {
        $id = rtrim(Yii::$app->request->post('str'), ',');
        $cid = rtrim(Yii::$app->request->post('cid'), ',');
        $res = Yii::$app->db->createCommand("DELETE FROM `shop_order` WHERE order_id in ($id)")
            ->execute();
        if ($res) {
//            Yii::$app->db->createCommand("DELETE FROM `consignee` WHERE consignee_id in ($cid)")
//                ->execute();
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 发货页面
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionOrderdetails()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $data = Yii::$app->db->createCommand("select * from shop_order as s left join consignee as c on s.consignee_id=c.consignee_id join express as e on s.express_id=e.express_id where s.order_id=:id")
            ->bindValue(':id', $id)
            ->queryOne();
        $uid = $data['submitter'];
        $user = Yii::$app->db->createCommand("select * from users where id=:id")
            ->bindValue(':id', $uid)
            ->queryOne();
        $data['submitter'] = $user;
        $arr = explode(',', $data['shop_name']);
        foreach ($arr as $value) {
            $idALL[] = explode('-', $value);
        }
        foreach ($idALL as $shop) {
            $good = Yii::$app->db->createCommand("select  shop_id,shop_name,shop_img from shop where shop_id=:id")
                ->bindValue(':id', $shop[0])
                ->queryOne();
            $good['num'] = $shop[1];
            $goods[] = $good;
        }
        $data['shop_name'] = $goods;
        return $this->RenderPartial('order-detailed', ['data' => $data]);
    }

    /**
     * 发货功能
     * @throws \yii\db\Exception
     */
    public function actionOrdershipments()
    {
        $request = Yii::$app->request;
        $id = $request->post('id');
        $express_num = $request->post('express_num');
        $express_id = $request->post('express_id');
        $res = Yii::$app->db->createCommand()->update('shop_order',
            ['express_id' => $express_id, 'express_num' => $express_num], 'order_id=' . $id)->execute();
        if ($res) {
            Yii::$app->db->createCommand()->update('shop_order',
                ['order_status' => '1'], 'order_id=' . $id)->execute();
            return 1;
        } else {
            return 0;
        }

    }


}